<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="./css/Carousel.css">
</head>

<body>
    <div>
        <ul id="nav">
            <li class="active"></li>
            <li></li>
            <li></li>
            <li></li>
        </ul>
        <ul id="img">
            <div class="imgbox">
                <li class="active"><img src="./image/01.png" alt="" /></li>
                <li><img src="./image/02.png" alt="" /></li>
                <li><img src="./image/03.png" alt="" /></li>
                <li><img src="./image/04.png" alt="" /></li>
            </div>
        </ul>
    </div>
    <script>
        var lis = document.querySelectorAll("#nav>li");
        var ban = document.querySelectorAll("#img>.imgbox>li");
        var banner = document.getElementsByClassName('imgbox')[0]
        var imgW = ban[0].clientWidth
        var bannerW = banner.clientWidth
        var ind = 0;
        var time = null

        // 清除类名，绑定导航点和图片
        for (var j = 0; j < lis.length; j++) {
            lis[j].dataset.index = j;
            lis[j].onclick = function () {
                for (var i = 0; i < lis.length; i++) {
                    lis[i].classList.remove("active");
                }
                this.classList.add("active");
                clearInterval(time)
                ind = this.dataset.index
                timeChange()
                next_img(this.dataset.index)
            };
        }

        // 定时切换
        function timeChange () {
            time = setInterval(function () {
                ind++;
                if (ind >= ban.length) {
                    ind = 0;
                }
                for (var i = 0; i < lis.length; i++) {
                    lis[i].classList.remove("active");
                }
                lis[ind].classList.add("active");
                next_img(ind)
            }, 2000);
        }
        timeChange()
        // 切换下一张
        function next_img (index) {
            var left = imgW * index
            if (left > bannerW - imgW) {
                left = 0
            }
            banner.style.left = -left + 'px'
        }
        // 切换上一张
        // function up_img (index) {
        //     var left = imgW * index
        //     if (left < 0) {
        //         left = 0
        //     }
        //     banner.style.left = left + 'px'
        // }
    </script>
</body>

</html>